import 'dart:async';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/ai_poster/ai_poster_index_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/bg_music/bg_music_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_mixin/navigator_page_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'bg_sys_recommend_music_page.dart';
import 'bg_terminal_music_list_page.dart';
import 'change_to_recommend_or_my_list_page_event.dart';

/// 背景音乐首页
class MusicIndexPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "MusicIndexPage";
  final String terminalName;
  final String hsn;
  final String hsns;
  const MusicIndexPage({Key key,this.terminalName, this.hsn, this.hsns}) : super(key: key);


  @override
  MusicIndexPageState createState() => MusicIndexPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context,
      String terminalName, String hsn, String hsns) {
    return RouterUtils.routeForFutureResult(
      context,
      MusicIndexPage(
        terminalName: terminalName,
        hsn: hsn,
        hsns: hsns,
      ),
      routeName: MusicIndexPage.ROUTER,
    );
  }
}

class MusicIndexPageState
    extends BasePagerState<AiPosterIndexListItemBean, MusicIndexPage>
    with
        AutomaticKeepAliveClientMixin,
        VgPlaceHolderStatusMixin,
        NavigatorPageMixin {

  BgMusicViewModel _viewModel;
  PageController _pageController;
  ValueNotifier<int> _pageValueNotifier;
  int _diyCount = 2;
  StreamSubscription _changePageStreamSubscription;
  bool _showMoreOperation = false;
  ///获取state
  static MusicIndexPageState of(BuildContext context) {
    final MusicIndexPageState result =
    context.findAncestorStateOfType<MusicIndexPageState>();
    return result;
  }

  bool showBubble = false;
  //水牌模板 00固定模板 01轮换模板
  String _moduleType = "01";
  @override
  void initState(){
    super.initState();
    _viewModel = new BgMusicViewModel(this);
    _pageValueNotifier = ValueNotifier(0);
    _pageController = PageController(keepPage: true, initialPage: 0);
    _pageController?.addListener(_setCurrentPage);
    //监听页面跳转
    _changePageStreamSubscription =
        VgEventBus.global.on<ChangeToRecommendOrMyListPageEvent>()?.listen((event) {
          _pageController.animateToPage(event.page, duration: Duration(milliseconds: 10), curve: Curves.linear);
        });
  }

  @override
  void dispose() {
    _changePageStreamSubscription?.cancel();
    _pageController?.removeListener(_setCurrentPage);
    _pageController?.dispose();
    _pageValueNotifier?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
          resizeToAvoidBottomInset: false,
          resizeToAvoidBottomPadding: false,
          backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
          body: Column(
            children: [
              _toTopBarWidget(),
              _toChangeWidget(),
              Expanded(child: _toPageWidget()),
            ],
          ),
        );
  }

  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: widget?.terminalName??"-",
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      titleColor: ThemeRepository.getInstance().getTextColor_D0E0F7(),
    );
  }


  ///切换
  Widget _toChangeWidget(){
    return ValueListenableBuilder(
        valueListenable: _pageValueNotifier,
        builder: (BuildContext context, int page, Widget child){
          return Container(
            height: 34,
            color: ThemeRepository.getInstance().getCardBgColor_21263C(),
            padding: EdgeInsets.symmetric(horizontal: 15),
            child: Container(
              width: ScreenUtils.screenW(context) - 30,
              height: 34,
              padding: EdgeInsets.all(3),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6),
                color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
              ),
              child: Row(
                children: [
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: (){
                      _animToPage(0);
                    },
                    child: Container(
                      width: (ScreenUtils.screenW(context) - 30 - 6)/2,
                      height: 28,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: (page == 0)?ThemeRepository.getInstance().getPrimaryColor_1890FF():
                        Colors.transparent,
                        borderRadius: (page == 0)?BorderRadius.circular(4):BorderRadius.circular(0),
                      ),
                      child: Text(
                        "背景音乐",
                        style: TextStyle(
                          color: (page == 0)?Colors.white:ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                          fontSize: 12,
                        ),
                      ),
                    ),
                  ),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: (){
                      _animToPage(1);
                    },
                    child: Container(
                      width: (ScreenUtils.screenW(context) - 30 - 6)/2,
                      height: 28,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: (page == 1)?ThemeRepository.getInstance().getPrimaryColor_1890FF():
                        Colors.transparent,
                        borderRadius: (page == 1)?BorderRadius.circular(4):BorderRadius.circular(0),
                      ),
                      child: Text(
                        "推荐音乐",
                        style: TextStyle(
                          color: (page == 1)?Colors.white:ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                          fontSize: 12,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        }
    );


  }

  void _animToPage(int page){
    if(page != 1 && page != 0){
      return;
    }
    _pageController?.animateToPage(page, duration: DEFAULT_ANIM_DURATION, curve: Curves.linear);
  }

  void _setCurrentPage(){
    if(_diyCount < 1){
      return;
    }
    if(_pageController.page >= 0.51){
      _pageValueNotifier.value = 1;
      print("_setCurrentPage:" + _pageValueNotifier.value.toString());
    }else if(_pageController.page <=0.49){
      _pageValueNotifier.value = 0;
      print("_setCurrentPage:" + _pageValueNotifier.value.toString());
    }

    // _pageValueNotifier.value = widget?.pageController?.page?.floor();
  }

  Widget _toPageWidget(){
    if(_diyCount>0){
      return PageView(
        controller: _pageController,
        physics: ClampingScrollPhysics(),
        children: <Widget>[
          BgTerminalMusicListPage(terminalName: widget?.terminalName, hsn: widget?.hsn, hsns: widget?.hsns,),
          BgSysRecommendMusicPage(hsn: widget?.hsn),
        ],
      );
    }else{
      return BgSysRecommendMusicPage(hsn: widget?.hsn);
    }

  }

  @override
  bool get wantKeepAlive => true;
}
